<template>
  <div class="root">

    <div class="card" v-if="flag == 'def' ? true : ''">
      <!-- 标题 -->
      <Nav :title="title"></Nav>
      <van-address-list :disabled-list="list" default-tag-text="默认" @add="onAdd" @edit-disabled="onEdit"
        @select-disabled="select">
      </van-address-list>

    </div>

    <!-- 编辑地址 -->
    <div class="edit" v-if="flag == 'edit' ? true : ''">
      <!-- 标题 -->
      <div class="header">
        <div class="header-box">
          <div class="header-l">
            <van-icon name="arrow-left" />
            <span @click="toAddress">返回</span>
          </div>

          <h2 class="header-m">编辑管理</h2>
          <div></div>
        </div>
      </div>
      <van-form @submit="onSubmit">
        <van-field v-model="name" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="tel" name="电话" label="电话" placeholder="电话" :rules="[{ required: true, message: '请填写密码' }]" />
        <van-field v-model="address" is-link readonly name="area" label="地区选择" placeholder="点击选择省市区"
          @click="showArea = true" />
        <van-popup v-model:show="showArea" position="bottom">
          <van-area :area-list="areaList" @confirm="onEditConfirm" @cancel="showArea = false" />
        </van-popup>
        <van-field v-model="addressDetail" name="详细地址" label="详细地址" placeholder="详细地址"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field name="switch" label="是否设置默认地址">
          <template #input>
            <van-switch v-model="isDefault" size="20" />
          </template>
        </van-field>

        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">提交</van-button>
        </div>
        <div style="margin: 16px" @click="onDelete">
          <van-button round block type="primary">删除</van-button>
        </div>
      </van-form>
    </div>

    <!-- 点击新增 -->
    <div class="addAddress" v-if="flag == 'add' ? true : ''">
      <div class="header">
        <div class="header-box">
          <div class="header-l">
            <van-icon name="arrow-left" />
            <span @click="toAddress">返回</span>
          </div>

          <h2 class="header-m">新增地址</h2>
          <div></div>
        </div>
      </div>
      <van-address-edit :area-list="areaList" show-set-default show-search-result :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" />
    </div>
  </div>
</template>

<script>

import { dele } from '@/mixin/index'
import { useRouter } from 'vue-router'
import { areaList } from '@vant/area-data'
import { useStore } from 'vuex'
import {
  getListAction, saveAction,
  deleteAction
} from '@/api/user/user'
import { ref, onMounted } from 'vue'
// import { useRouter } from 'vue-router'
export default {
  name: 'AddressApi',
  setup () {
    const router = useRouter()
    const store = useStore()
    const id = ref('')
    const arr = ref([])
    const isDefault = ref(false)
    const deleId = ref('')
    const address = ref('')
    const flag = ref('')
    const searchResult = ref([])
    const name = ref('')
    const tel = ref('')
    const addressDetail = ref('')
    const list = ref([])
    const showArea = ref(false)
    const title = ref('地址管理')
    function a () {
      flag.value = 'def'
      // 渲染初始列表
      getListAction({
        openId: localStorage.getItem('openId')
      }).then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].is_default === 1) {
            res.data[i].is_default = true
          } else {
            res.data[i].is_default = false
          }
          res.data[i].isDefault = res.data[i].is_default
        }
        // 替换data里的mobile
        res.data = JSON.parse(
          JSON.stringify(res.data).replace(/mobile/g, 'tel')
        )
        //   let c =  res.data.map(function (e) {
        //       return { tel: e.mobile };
        //     });
        //     console.log(c);
        console.log(res.data)
        list.value = res.data
      })
    }
    a()
    onMounted(() => {
      flag.value = 'def'
      a()
    })
    const onEditConfirm = ({ selectedOptions }) => {
      showArea.value = false
      address.value = selectedOptions.map((item) => item.text).join('/')
    }
    const onConfirm = (values) => {
      console.log('12', values)
      address.value = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join('/')
      showArea.value = false
    }
    const toAddress = () => {
      title.value = '新增地址'
      a()
    }
    const onAdd = () => {
      flag.value = 'add'
    }
    const onSave = (content) => {
      address.value = content.province.concat(
        ',',
        content.city,
        ',',
        content.county
      )
      const fn = () => {
        saveAction({
          userName: content.name,
          telNumber: content.tel,
          detailadress: content.addressDetail,
          checked: content.isDefault,
          address: address.value,
          addressId: '',
          openId: localStorage.getItem('openId')
        }).then((res) => {
          console.log(res)
          a()
        })
      }
      dele('是否添加', fn)
    }
    // 编辑
    const onEdit = (item) => {
      // 点击图标后改变flag,传递页面信息与id
      title.value = '地址编辑'
      flag.value = 'edit'
      address.value = item.address
      name.value = item.name
      tel.value = item.tel
      isDefault.value = item.isDefault
      addressDetail.value = item.address_detail
      id.value = item.id
    }
    const onSubmit = () => {
      saveAction({
        userName: name.value,
        telNumber: tel.value,
        detailadress: addressDetail.value,
        checked: isDefault.value,
        address: address.value,
        addressId: id.value,
        openId: localStorage.getItem('openId')
      }).then((res) => {
        console.log(res)
      })
      a()
    }
    // 删除地址
    const onDelete = () => {
      const fn = () => {
        deleteAction({
          id: id.value
        }).then(res => {
          console.log(res)
          a()
        })
      }
      dele('是否删除这个地址', fn)
    }
    // 点击跳转
    const select = (item) => {
      store.commit('reAddress', item.id)
      router.go(-1)
      console.log('12')
    }
    return { id, arr, isDefault, searchResult, address, flag, name, tel, list, showArea, onEdit, addressDetail, deleId, onConfirm, toAddress, onAdd, onSave, select, onSubmit, onDelete, areaList, onEditConfirm, title }
  }
}
</script>

<style lang="scss" scoped>
@import './scss/index.scss'
</style>
